package com.cqeec.myblog.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cqeec.myblog.model.Category;
import com.cqeec.myblog.service.CategoryService;
import com.cqeec.myblog.service.CategoryServiceImpl;
import com.cqeec.myblog.util.JsonUtils;

/**
 * Servlet implementation class FindAllCategory
 */
@WebServlet("/categoryServlet")
public class CategoryServlet extends HttpServlet {
	CategoryService categoryService=new CategoryServiceImpl();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String operation  =request.getParameter("operation");
		//ajax查询所有分类操作
		if("findAllCategory".equals(operation)) {
			//获取所有分类
			List<Category> categoryList=categoryService.getAllCategory();
			//将list集合转换为json数组
			String jsonObj=JsonUtils.objectToJson(categoryList);
			//将分类信息封装为json串传回客户端
			response.getWriter().write(jsonObj);
			return;
		}
		
		//ajax根据id删除指定分类
		if("deleteCategoryByCid".equals(operation)) {
			 String cid=request.getParameter("cid"); 
			 categoryService.deleteCategoryByCid(cid);
			 Map<String, Object> map=new HashMap<>();
			 map.put("flag",true);
			 String jsonObj=JsonUtils.objectToJson(map);
			 response.getWriter().write(jsonObj);
			 return;
		}
		
		
		//ajax添加分类
		if("addCateogy".equals(operation)) {
			String cname=request.getParameter("cname");
			String cid=UUID.randomUUID().toString();
			//判断是否数据库中有相同的数据()
			boolean flag=categoryService.findByCname(cname);
			Map<String, Object> map=new HashMap<>();
			//如果没有则往数据库中添加客户端填写的数据
			if(!flag) {
				categoryService.addCategory(cid,cname);
				map.put("cid", cid);
				map.put("cname",cname);
			}
			//返回json参数给客户端
			map.put("flag",flag);
			String jsonObj=JsonUtils.objectToJson(map);
			response.getWriter().write(jsonObj);
			return;
		}
		
		
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
